﻿#include "HolidayOptionDelegate.h"
#include <QComboBox>
#include <QDateEdit>
#include "Tools.h"

HolidayOptionDelegate::HolidayOptionDelegate(QObject *parent)
	: QItemDelegate(parent)
{
}

HolidayOptionDelegate::~HolidayOptionDelegate()
{
}
QWidget* HolidayOptionDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
	if (index.column() == 0)           //第1列 班级
	{
		QComboBox   *Cbox = new QComboBox(parent);
		Cbox->addItem(QString::fromWCharArray(L"节日"));
		Cbox->addItem(QString::fromWCharArray(L"特殊工作日"));
		return Cbox;
	}
	if (index.column() == 1 || index.column() == 2)
	{
		QDateTimeEdit *pDtEdit = new QDateTimeEdit(parent);
		pDtEdit->setDate(QDate::currentDate());
		return pDtEdit;
	}

	return QItemDelegate::createEditor(parent, option, index);      //第0列,则选择默认编辑器
}

void HolidayOptionDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const
{
	if (index.column() == 0)           //第1列 班级
	{
		QComboBox   *Cbox = dynamic_cast<QComboBox*>(editor);
		Cbox->setCurrentIndex(Cbox->findText(index.data(Qt::DisplayRole).toString()));
		return;
	}
	if (index.column() == 1 || index.column() == 2)
	{
		QDateTimeEdit *pDtEdit = dynamic_cast<QDateTimeEdit*>(editor);
		QString datetimeStr = index.data(Qt::DisplayRole).toString();
		tm tmDatetime = Tools::DateStr2TM(datetimeStr.toLocal8Bit().data());
		time_t tmDatetimeStamp = Tools::GetTimeStamp(tmDatetime);
		pDtEdit->setDateTime(QDateTime::fromTime_t(tmDatetimeStamp));
		return;
	}
	QItemDelegate::setEditorData(editor, index);
}

void HolidayOptionDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const
{
	if (index.column() == 0)           //第1列 班级
	{
		QComboBox   *Cbox = dynamic_cast<QComboBox*>(editor);
		model->setData(index, Cbox->currentText(), Qt::DisplayRole);
		return;
	}
	if (index.column() == 1 || index.column() == 2)
	{
		QDateTimeEdit *pDtEdit = dynamic_cast<QDateTimeEdit*>(editor);
		time_t cutmStamp = pDtEdit->dateTime().toTime_t();
		tm cuTm = Tools::GetDateTimeFrmStamp(cutmStamp);
		std::string cuTmStr = Tools::DateToStr(cuTm);
		model->setData(index, QString::fromLocal8Bit(cuTmStr.c_str()), Qt::DisplayRole);
		return;
	}
	QItemDelegate::setModelData(editor, model, index);
}

void HolidayOptionDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
	editor->setGeometry(option.rect);
}